import { _decorator, ICollisionEvent, Vec3 } from 'cc';
const { ccclass, property } = _decorator;
import { BilliardGame } from './BilliardGame';
import { BaseBallSphere } from './BaseBallSphere';
import { EventManager } from '../core/EventManager';

@ccclass('BallSphere')
export class BallSphere extends BaseBallSphere {
  onLoad() {
    super.onLoad();
    // 球刚体
    this.ballCollider.on('onCollisionEnter', this.onCollisionEnter, this);
    this.ballCollider.on('onCollisionStay', this.onCollisionStay, this);
    this.ballCollider.on('onCollisionExit', this.onCollisionExit, this);

    EventManager.Instance().AddEventListener('ResetBallPosition', this, this.resetBallPosition);
    EventManager.Instance().AddEventListener('InitBallPosition', this, this.initBallPosition);
    EventManager.Instance().AddEventListener('HideBallByName', this, this.hideBallByName);
  }
  start() {
  }
  update(deltaTime: number) {
    super.update(deltaTime);
  }

  public initBallPosition(name: string, ball: { ballName: string, pos: Vec3 }) {
    // 所有的球实体，都会收到这个消息
    if (ball.ballName !== this.node.name) {
      return;
    }
    this.node.setPosition(ball.pos);
    this.outHole();
  }

  public resetBallPosition(name: string, ball: { ballName: string, pos: Vec3 }) {
    // 所有的球实体，都会收到这个消息
    if (ball.ballName !== this.node.name) {
      return;
    }
    var pos = new Vec3(ball.pos.x, ball.pos.y, ball.pos.z);
    this.node.setPosition(this.getNoCollisionBallPosition(ball.ballName, pos));
    this.outHole();
  }
  public hideBallByName(name: string, ballName: string) {
    if (ballName !== this.node.name) {
      return;
    }
    this.node.active = false;
    this.hasInHole = true;
  }
  public onCollisionEnter(event: ICollisionEvent) {
    super.onCollisionEnter(event);
  }

  public onCollisionStay(event: ICollisionEvent) {
  }
  public onCollisionExit(event: ICollisionEvent) {
  }

  public getNoCollisionBallPosition(ballName: string, pos: Vec3) {
    const balls = BilliardGame.Instance().getActiveBalls();
    const offsetz = [pos.z, 0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5];
    for (const z of offsetz) {
      var hasCollision = false;
      const posz = z;
      for (const ball of balls) {
        if (ballName === ball.name) continue;
        const dist = (ball.worldPosition.x - pos.x) * (ball.worldPosition.x - pos.x)
          + (ball.worldPosition.z - posz) * (ball.worldPosition.z - posz);
        if (dist < 1.000001) {
          hasCollision = true;
          break;
        }
      }
      if (!hasCollision) {
        pos.z = posz;
        return pos;
      }
    }
    return pos;
  }
}

